

package com.maoshi.shop.api.controller;

import com.alipay.api.AlipayApiException;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.maoshi.shop.bean.bo.PayInfoBo;
import com.maoshi.shop.common.enums.PayType;
import com.maoshi.shop.bean.model.Order;
import com.maoshi.shop.bean.model.OrderItem;
import com.maoshi.shop.service.PayManagerService;
import com.maoshi.shop.service.PayService;
import com.maoshi.shop.service.ProductService;
import com.maoshi.shop.service.SkuService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

@ApiIgnore
@RestController
@RequestMapping("/notice/pay")
@AllArgsConstructor
public class PayNoticeController {

    private final PayService payService;

    private final ProductService productService;

    private final SkuService skuService;

    private final PayManagerService payManagerService;



    /**
     * 微信异步回调
     */
    @RequestMapping("/order/{payType}")
    public ResponseEntity<Void> submit(HttpServletRequest request, @PathVariable Integer payType, @RequestBody String xmlData) throws WxPayException, UnsupportedEncodingException, AlipayApiException {


        PayInfoBo payInfoBo = payManagerService.validateAndGetPayInfo(request,PayType.instance(payType),xmlData);

        // 根据内部订单号更新order settlement
        List<Order> orders = payService.paySuccess(payInfoBo.getPayNo(), payInfoBo.getBizPayNo());

        // 移除缓存
        for (Order order : orders) {
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                productService.removeProductCacheByProdId(orderItem.getProdId());
                skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
            }
        }

        return ResponseEntity.ok().build();
    }

}
